package com.example.ai.service;

import com.alibaba.fastjson.JSONObject;
import com.example.ai.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class QwenService {

    @Value("${aliyun.dashscope.api-key}")
    private String apiKey;

    public String chat(String userQuestion) {
        long start = System.currentTimeMillis();

        // 构建请求体
        JSONObject jsonData = new JSONObject();
        jsonData.put("model", "qwen1.5-110b-chat");

        JSONObject input = new JSONObject();
        JSONObject message = new JSONObject();
        message.put("role", "user");
        message.put("content", userQuestion);
        input.put("messages", new JSONObject[]{message});

        jsonData.put("input", input);
        jsonData.put("parameters", new JSONObject());

        // 设置请求头
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Authorization", "Bearer " + apiKey);
        headerMap.put("Content-Type", "application/json");
        headerMap.put("X-DashScope-SSE", "enable");

        // 发送请求
        String url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
        String response = HttpUtils.executePost(url, jsonData.toJSONString(), headerMap);

        try {
            // 解析响应
            int index = response.lastIndexOf("data:");
            if (index == -1) {
                log.error("Invalid AI response format: {}", response);
                return "抱歉，AI 响应格式错误";
            }

            String jsonStr = response.substring(index + 5, response.length() - 1);
            JSONObject jsonObject = JSONObject.parseObject(jsonStr);
            String aiResponse = jsonObject.getJSONObject("output").getString("text");

            log.info("AI response cost {}ms, question: {}, response: {}",
                    System.currentTimeMillis() - start, userQuestion, aiResponse);

            return aiResponse;

        } catch (Exception e) {
            log.error("Error parsing AI response", e);
            return "抱歉，处理 AI 响应时出错";
        }
    }
} 